<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>餐厅导航 - 美食社区</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
    <!-- 高德地图 API 配置 -->
    <script>
        window._AMapSecurityConfig = {
            securityJsCode: '改成你的密钥',
        }
    </script>
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=改成你的key"></script>
    <script src="https://webapi.amap.com/ui/1.1/main.js"></script>
    <style>
        #map {
            height: calc(100vh - 56px);
            width: 100%;
            position: fixed;
            top: 56px;
            left: 0;
            z-index: 1;
        }

        .filter-panel {
            position: fixed;
            top: 76px;
            left: 20px;
            z-index: 2;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            width: 300px;
            max-height: calc(100vh - 100px);
            overflow-y: auto;
        }

        .restaurant-info-panel {
            position: fixed;
            top: 76px;
            right: 20px;
            z-index: 2;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            width: 350px;
            max-height: calc(100vh - 100px);
            overflow-y: auto;
            display: none;
        }

        .restaurant-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 5px;
            margin-bottom: 15px;
        }

        .rating-stars {
            color: #ffc107;
        }

        .price-level {
            color: #28a745;
        }

        .btn-primary {
            background-color: #fd7e14;
            border-color: #fd7e14;
        }

        .btn-primary:hover {
            background-color: #e76b00;
            border-color: #e76b00;
        }

        .close-panel {
            position: absolute;
            top: 10px;
            right: 10px;
            cursor: pointer;
            font-size: 18px;
            color: #6c757d;
        }

        .close-panel:hover {
            color: #343a40;
        }

        .cuisine-badge {
            background-color: #fff3e6;
            color: #fd7e14;
            border: 1px solid #ffd7b5;
            border-radius: 20px;
            padding: 5px 15px;
            margin: 5px;
            display: inline-block;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .cuisine-badge:hover,
        .cuisine-badge.active {
            background-color: #fd7e14;
            color: white;
            border-color: #fd7e14;
        }

        .toggle-filter {
            position: fixed;
            top: 76px;
            left: 20px;
            z-index: 3;
            background-color: white;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            display: none;
        }

        /* 评分输入样式 */
        .rating-input {
            display: flex;
            font-size: 24px;
            color: #ffc107;
            cursor: pointer;
        }

        .rating-input i {
            margin-right: 5px;
        }

        .rating-input i:hover~i {
            color: #6c757d;
        }

        @media (max-width: 768px) {
            .filter-panel {
                display: none;
                width: 100%;
                left: 0;
                top: 56px;
                border-radius: 0;
            }

            .restaurant-info-panel {
                width: 100%;
                right: 0;
                top: 56px;
                border-radius: 0;
            }

            .toggle-filter {
                display: flex;
            }
        }

        /* 高德地图信息窗口样式 */
        .amap-info-content {
            padding: 10px;
            border-radius: 5px;
        }
    </style>
</head>

<body>
    <!-- 存储当前用户信息 -->
    <div id="currentUsername" style="display: none;" th:if="${session.user != null}"
        th:data-username="${session.user.username}"></div>

    <!-- 导航栏 -->
    <nav th:replace="~{common/header :: header}"></nav>

    <!-- 地图 -->
    <div id="map"></div>

    <!-- 筛选面板切换按钮 -->
    <div class="toggle-filter" id="toggleFilter">
        <i class="fas fa-filter"></i>
    </div>

    <!-- 筛选面板 -->
    <div class="filter-panel" id="filterPanel">
        <h5>筛选餐厅</h5>
        <div class="mb-3">
            <div class="d-flex flex-wrap">
                <span class="cuisine-badge active" data-cuisine="">全部</span>
                <span class="cuisine-badge" data-cuisine="中餐">中餐</span>
                <span class="cuisine-badge" data-cuisine="西餐">西餐</span>
                <span class="cuisine-badge" data-cuisine="日料">日料</span>
                <span class="cuisine-badge" data-cuisine="韩餐">韩餐</span>
                <span class="cuisine-badge" data-cuisine="烘焙">烘焙</span>
                <span class="cuisine-badge" data-cuisine="小吃">小吃</span>
            </div>
        </div>
        <form id="filterForm">
            <div class="mb-3">
                <label class="form-label">菜系类型</label>
                <select class="form-select" name="cuisineType" id="cuisineType">
                    <option value="">全部</option>
                    <option value="中餐">中餐</option>
                    <option value="西餐">西餐</option>
                    <option value="日料">日料</option>
                    <option value="韩餐">韩餐</option>
                    <option value="烘焙">烘焙</option>
                    <option value="小吃">小吃</option>
                    <option value="其他">其他</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">价格区间</label>
                <select class="form-select" name="minPrice" id="minPrice">
                    <option value="">不限</option>
                    <option value="1">¥ (便宜)</option>
                    <option value="2">¥¥ (适中)</option>
                    <option value="3">¥¥¥ (昂贵)</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">最低评分</label>
                <select class="form-select" name="minRating" id="minRating">
                    <option value="">不限</option>
                    <option value="4.5">4.5分以上</option>
                    <option value="4.0">4.0分以上</option>
                    <option value="3.5">3.5分以上</option>
                    <option value="3.0">3.0分以上</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary w-100">应用筛选</button>
        </form>
    </div>

    <!-- 餐厅信息面板 -->
    <div class="restaurant-info-panel" id="restaurantInfoPanel">
        <i class="fas fa-times close-panel" id="closeInfoPanel"></i>
        <div id="restaurantInfo">
            <!-- 餐厅信息将通过JavaScript动态填充 -->
        </div>
    </div>

    <!-- 添加餐厅按钮 -->
    <div style="position: fixed; bottom: 20px; right: 20px; z-index: 999;">
        <button id="addRestaurantBtn" class="btn btn-primary rounded-circle"
            style="width: 60px; height: 60px; box-shadow: 0 2px 10px rgba(0,0,0,0.2);">
            <i class="fas fa-plus fa-lg"></i>
        </button>
    </div>

    <!-- 添加/编辑餐厅模态框 -->
    <div class="modal fade" id="restaurantModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="restaurantModalTitle">添加餐厅</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="restaurantForm">
                        <input type="hidden" id="restaurantId">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="restaurantName" class="form-label">餐厅名称 <span
                                        class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="restaurantName" required>
                            </div>
                            <div class="col-md-6">
                                <label for="restaurantCuisineType" class="form-label">菜系类型 <span
                                        class="text-danger">*</span></label>
                                <select class="form-select" id="restaurantCuisineType" required>
                                    <option value="">请选择菜系</option>
                                    <option value="中餐">中餐</option>
                                    <option value="西餐">西餐</option>
                                    <option value="日料">日料</option>
                                    <option value="韩餐">韩餐</option>
                                    <option value="烘焙">烘焙</option>
                                    <option value="小吃">小吃</option>
                                    <option value="其他">其他</option>
                                </select>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="restaurantAddress" class="form-label">地址 <span
                                        class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="restaurantAddress" required>
                            </div>
                            <div class="col-md-6">
                                <label for="restaurantPriceLevel" class="form-label">价格等级 <span
                                        class="text-danger">*</span></label>
                                <select class="form-select" id="restaurantPriceLevel" required>
                                    <option value="1">¥ (便宜)</option>
                                    <option value="2">¥¥ (适中)</option>
                                    <option value="3">¥¥¥ (昂贵)</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="restaurantDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="restaurantDescription" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="restaurantImage" class="form-label">图片</label>
                            <input type="file" class="form-control" id="restaurantImage" accept="image/*">
                            <div id="imagePreview" class="mt-2" style="max-width: 300px;"></div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-12">
                                <label class="form-label">位置 <span class="text-danger">*</span></label>
                                <div id="pickLocationMap" style="height: 300px;"></div>
                                <div class="form-text mt-2">点击地图选择餐厅位置</div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <label for="restaurantLatitude" class="form-label">纬度</label>
                                <input type="text" class="form-control" id="restaurantLatitude" readonly>
                            </div>
                            <div class="col-md-6">
                                <label for="restaurantLongitude" class="form-label">经度</label>
                                <input type="text" class="form-control" id="restaurantLongitude" readonly>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveRestaurantBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加评论模态框 -->
    <div class="modal fade" id="reviewModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加评论</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="reviewForm">
                        <input type="hidden" id="reviewRestaurantId">
                        <div class="mb-3">
                            <label class="form-label">评分 <span class="text-danger">*</span></label>
                            <div class="rating-input">
                                <i class="far fa-star" data-rating="1"></i>
                                <i class="far fa-star" data-rating="2"></i>
                                <i class="far fa-star" data-rating="3"></i>
                                <i class="far fa-star" data-rating="4"></i>
                                <i class="far fa-star" data-rating="5"></i>
                                <input type="hidden" id="reviewRating" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="reviewContent" class="form-label">评论内容 <span
                                    class="text-danger">*</span></label>
                            <textarea class="form-control" id="reviewContent" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="reviewImages" class="form-label">上传图片</label>
                            <input type="file" class="form-control" id="reviewImages" multiple accept="image/*">
                            <div id="reviewImagePreview" class="mt-2 d-flex flex-wrap gap-2"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveReviewBtn">提交评论</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <!-- 退出登录脚本 -->
    <script th:replace="~{common/header :: logout-script}"></script>

    <script>
        $(document).ready(function () {
            // 检查当前用户是否为管理员
            let isAdmin = false;

            // 从 session 中获取用户信息
            const userElement = document.getElementById('currentUsername');
            if (userElement) {
                const username = userElement.getAttribute('data-username');
                isAdmin = username === 'admin';
            }

            // 根据用户权限控制添加餐厅按钮的显示
            if (!isAdmin) {
                $('#addRestaurantBtn').parent().hide();
            }

            // 初始化高德地图
            const map = new AMap.Map('map', {
                zoom: 12,
                center: [104.195397, 35.86166], // 中国中心点
                resizeEnable: true,
                viewMode: '2D'  // 设置为2D模式
            });

            console.log("地图初始化完成");

            // 添加地图控件
            map.plugin(['AMap.ToolBar', 'AMap.Scale'], function () {
                map.addControl(new AMap.ToolBar());
                map.addControl(new AMap.Scale());
                console.log("地图控件添加完成");
            });

            // 确保地图加载完成后再加载标记
            map.on('complete', function () {
                console.log("地图完全加载完成，开始加载标记");
                // 初始加载所有餐厅标记
                loadMarkers();
            });

            // 全局变量存储所有标记
            let allMarkers = [];

            // 获取餐厅标记
            function loadMarkers(params = {}) {
                $.ajax({
                    url: '/api/food-map/markers',
                    type: 'GET',
                    data: params,
                    success: function (res) {
                        if (res.code === 200) {
                            console.log("加载餐厅数据:", res.data.length, "条记录");

                            // 检查数据是否包含经纬度
                            const validData = res.data.filter(restaurant =>
                                restaurant.latitude && restaurant.longitude);

                            console.log("有效经纬度数据:", validData.length, "条记录");

                            if (validData.length === 0) {
                                clearAllMarkers();

                                console.warn("没有有效的经纬度数据，无法显示标记");
                                return;
                            }

                            // 清除现有标记
                            clearAllMarkers();

                            const markers = [];
                            validData.forEach(function (restaurant) {
                                console.log("处理餐厅:", restaurant.name,
                                    "经度:", restaurant.longitude,
                                    "纬度:", restaurant.latitude,
                                    "评分:", restaurant.rating);

                                try {
                                    // 确保经纬度是数值类型
                                    const lng = parseFloat(restaurant.longitude);
                                    const lat = parseFloat(restaurant.latitude);

                                    if (isNaN(lng) || isNaN(lat)) {
                                        console.error("经纬度无效:", restaurant.name, lng, lat);
                                        return;
                                    }

                                    // 直接在地图上添加标记，不使用聚合
                                    // 根据评分设置不同的图标样式
                                    let iconUrl;
                                    let iconSize = [25, 34]; // 默认大小 [宽度, 高度]

                                    if (restaurant.rating >= 4.5) {
                                        console.log("高评分餐厅(>=4.5):", restaurant.name);
                                        iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png';
                                        iconSize = [35, 44];
                                    } else if (restaurant.rating >= 4.0) {
                                        console.log("中评分餐厅(>=4.0):", restaurant.name);
                                        iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/mark_g.png';
                                        iconSize = [30, 39];
                                    } else {
                                        iconUrl = 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png';
                                    }

                                    // 创建标记
                                    const marker = new AMap.Marker({
                                        position: [lng, lat],
                                        title: restaurant.name,
                                        map: map,  // 直接添加到地图上
                                        extData: restaurant.id,
                                        offset: new AMap.Pixel(-iconSize[0] / 2, -iconSize[1])
                                    });

                                    // 设置图标
                                    marker.setIcon(new AMap.Icon({
                                        size: new AMap.Size(iconSize[0], iconSize[1]),
                                        image: iconUrl,
                                        imageSize: new AMap.Size(iconSize[0], iconSize[1])
                                    }));

                                    // 创建信息窗体
                                    const infoWindow = new AMap.InfoWindow({
                                        content: `
                                            <div style="padding: 8px 0;">
                                                <h5 style="margin:0;">${restaurant.name}</h5>
                                                <div style="display: flex; align-items: center; margin-top: 5px;">
                                                    <span style="color: #ffc107; margin-right: 5px;">
                                                        ${restaurant.rating} <i class="fas fa-star"></i>
                                                    </span>
                                                    <span style="color: #28a745; margin-right: 5px;">
                                                        ${'¥'.repeat(restaurant.priceLevel)}
                                                    </span>
                                                    <span>${restaurant.cuisineType}</span>
                                                </div>
                                            </div>
                                        `,
                                        offset: new AMap.Pixel(0, -30)
                                    });

                                    // 点击标记时显示信息窗体并加载餐厅详情
                                    marker.on('click', function () {
                                        infoWindow.open(map, marker.getPosition());
                                        showRestaurantInfo(restaurant.id);
                                    });

                                    markers.push(marker);
                                    allMarkers.push(marker); // 添加到全局标记数组
                                    console.log("成功添加标记:", restaurant.name);
                                } catch (error) {
                                    console.error("创建标记失败:", error, restaurant);
                                }
                            });

                            console.log("创建标记数量:", markers.length);

                            // 如果有标记，调整地图视图以显示所有标记
                            if (markers.length > 0) {
                                const bounds = new AMap.Bounds();
                                markers.forEach(marker => {
                                    bounds.extend(marker.getPosition());
                                });
                                map.setBounds(bounds, true, [50, 50, 50, 50]);
                                console.log("地图视图已调整");
                            }
                        } else {
                            console.error("API返回错误:", res.msg);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error("API请求失败:", status, error);
                    }
                });
            }

            // 清除所有标记
            function clearAllMarkers() {
                if (allMarkers.length > 0) {
                    allMarkers.forEach(marker => {
                        marker.setMap(null);
                    });
                    allMarkers = [];
                    console.log("已清除所有标记");
                }
            }

            // 显示餐厅详细信息
            function showRestaurantInfo(restaurantId) {
                $.ajax({
                    url: `/api/food-map/restaurant/${restaurantId}`,
                    type: 'GET',
                    success: function (res) {
                        if (res.code === 200) {
                            const restaurant = res.data;

                            let html = `
                                <img src="${restaurant.image}" class="restaurant-image" alt="${restaurant.name}">
                                <h4>${restaurant.name}</h4>
                                <div class="d-flex align-items-center mb-3">
                                    <div class="rating-stars me-3">
                                        <span>${restaurant.rating}</span>
                                        <i class="fas fa-star"></i>
                                    </div>
                                    <div class="price-level me-3">
                                        <span>${'¥'.repeat(restaurant.priceLevel)}</span>
                                    </div>
                                    <span class="badge bg-light text-dark">${restaurant.cuisineType}</span>
                                </div>
                                <p><i class="fas fa-map-marker-alt me-2 text-primary"></i>${restaurant.address}</p>
                                <p><i class="fas fa-info-circle me-2 text-primary"></i>${restaurant.description}</p>
                                <div class="d-grid gap-2">
                                    <a href="/restaurant/${restaurant.id}" class="btn btn-primary">
                                        <i class="fas fa-info-circle me-2"></i>查看详情
                                    </a>
                                    <button class="btn btn-outline-primary add-review-btn" data-restaurant-id="${restaurant.id}">
                                        <i class="fas fa-comment me-2"></i>添加评论
                                    </button>`;

                            // 只有管理员才能看到编辑按钮
                            if (isAdmin) {
                                html += `
                                    <button class="btn btn-outline-secondary edit-restaurant-btn" data-restaurant-id="${restaurant.id}">
                                        <i class="fas fa-edit me-2"></i>编辑餐厅
                                    </button>`;
                            }

                            html += `</div>`;

                            $('#restaurantInfo').html(html);
                            $('#restaurantInfoPanel').show();

                            // 绑定添加评论按钮事件
                            $('.add-review-btn').click(function () {
                                const restaurantId = $(this).data('restaurant-id');
                                openReviewModal(restaurantId);
                            });

                            // 绑定编辑餐厅按钮事件
                            $('.edit-restaurant-btn').click(function () {
                                const restaurantId = $(this).data('restaurant-id');
                                openEditRestaurantModal(restaurantId);
                            });
                        }
                    }
                });
            }

            // 关闭餐厅信息面板
            $('#closeInfoPanel').click(function () {
                $('#restaurantInfoPanel').hide();
            });

            // 筛选表单提交
            $('#filterForm').submit(function (e) {
                e.preventDefault();

                const params = {
                    cuisineType: $('#cuisineType').val(),
                    minPrice: $('#minPrice').val() || undefined,
                    maxPrice: $('#maxPrice').val() || undefined,
                    minRating: $('#minRating').val() || undefined
                };

                loadMarkers(params);
            });

            // 快速菜系筛选
            $('.cuisine-badge').click(function () {
                const cuisine = $(this).data('cuisine');
                $('.cuisine-badge').removeClass('active');
                $(this).addClass('active');
                $('#cuisineType').val(cuisine);
                $('#filterForm').submit();
            });

            // 切换筛选面板显示
            $('#toggleFilter').click(function () {
                $('#filterPanel').toggle();
            });

            // 响应式处理
            $(window).resize(function () {
                if ($(window).width() <= 768) {
                    $('#filterPanel').hide();
                    $('#toggleFilter').show();
                } else {
                    $('#filterPanel').show();
                    $('#toggleFilter').hide();
                }
            });

            // 初始响应式状态
            if ($(window).width() <= 768) {
                $('#filterPanel').hide();
                $('#toggleFilter').show();
            }

            // 添加餐厅按钮点击事件
            $('#addRestaurantBtn').click(function () {
                openAddRestaurantModal();
            });

            // 初始化位置选择地图
            let pickLocationMap;
            let pickLocationMarker;

            // 打开添加餐厅模态框
            function openAddRestaurantModal() {
                // 重置表单
                $('#restaurantForm')[0].reset();
                $('#restaurantId').val('');
                $('#restaurantModalTitle').text('添加餐厅');
                $('#imagePreview').empty();

                // 显示模态框
                const restaurantModal = new bootstrap.Modal(document.getElementById('restaurantModal'));
                restaurantModal.show();

                // 模态框显示后初始化地图，确保地图容器已经可见
                restaurantModal._element.addEventListener('shown.bs.modal', function () {
                    console.log("模态框已显示，初始化位置选择地图");

                    // 初始化位置选择地图，默认显示中国
                    if (!pickLocationMap) {
                        pickLocationMap = new AMap.Map('pickLocationMap', {
                            zoom: 4,
                            center: [104.195397, 35.86166], // 中国中心点
                            resizeEnable: true,
                            viewMode: '2D'
                        });

                        // 点击地图选择位置
                        pickLocationMap.on('click', function (e) {
                            const lnglat = e.lnglat;
                            setPickLocationMarker(lnglat);
                        });

                        console.log("位置选择地图初始化完成");
                    } else {
                        // 如果地图已经初始化，则重新设置中心点和缩放级别
                        pickLocationMap.setCenter([104.195397, 35.86166]);
                        pickLocationMap.setZoom(4);
                        console.log("位置选择地图重新居中");
                    }

                    // 清除之前的标记
                    if (pickLocationMarker) {
                        pickLocationMarker.setMap(null);
                        pickLocationMarker = null;
                    }
                }, { once: true }); // 只监听一次事件
            }

            // 打开编辑餐厅模态框
            function openEditRestaurantModal(restaurantId) {
                // 获取餐厅信息
                $.ajax({
                    url: `/api/food-map/restaurant/${restaurantId}`,
                    type: 'GET',
                    success: function (res) {
                        if (res.code === 200) {
                            const restaurant = res.data;

                            // 填充表单
                            $('#restaurantId').val(restaurant.id);
                            $('#restaurantName').val(restaurant.name);
                            $('#restaurantCuisineType').val(restaurant.cuisineType);
                            $('#restaurantAddress').val(restaurant.address);
                            $('#restaurantPriceLevel').val(restaurant.priceLevel);
                            $('#restaurantDescription').val(restaurant.description);
                            $('#restaurantLatitude').val(restaurant.latitude);
                            $('#restaurantLongitude').val(restaurant.longitude);

                            // 显示图片预览
                            if (restaurant.image) {
                                $('#imagePreview').html(`<img src="${restaurant.image}" class="img-fluid">`);
                            } else {
                                $('#imagePreview').empty();
                            }

                            // 更新模态框标题
                            $('#restaurantModalTitle').text('编辑餐厅');

                            // 显示模态框
                            const restaurantModal = new bootstrap.Modal(document.getElementById('restaurantModal'));
                            restaurantModal.show();

                            // 确保经纬度是数值类型
                            const lng = parseFloat(restaurant.longitude);
                            const lat = parseFloat(restaurant.latitude);

                            // 模态框显示后初始化地图
                            restaurantModal._element.addEventListener('shown.bs.modal', function () {
                                console.log("模态框已显示，初始化位置选择地图");

                                // 初始化位置选择地图
                                if (!pickLocationMap) {
                                    pickLocationMap = new AMap.Map('pickLocationMap', {
                                        zoom: 15,
                                        center: [lng, lat],
                                        resizeEnable: true,
                                        viewMode: '2D'
                                    });

                                    // 点击地图选择位置
                                    pickLocationMap.on('click', function (e) {
                                        const lnglat = e.lnglat;
                                        setPickLocationMarker(lnglat);
                                    });

                                    console.log("位置选择地图初始化完成");
                                } else {
                                    // 如果地图已经初始化，则重新设置中心点和缩放级别
                                    pickLocationMap.setCenter([lng, lat]);
                                    pickLocationMap.setZoom(15);
                                    console.log("位置选择地图重新居中");
                                }

                                // 设置标记
                                setPickLocationMarker(new AMap.LngLat(lng, lat));
                            }, { once: true }); // 只监听一次事件
                        }
                    }
                });
            }

            // 设置位置选择标记
            function setPickLocationMarker(lnglat) {
                console.log("设置位置标记:", lnglat.getLng(), lnglat.getLat());

                // 清除之前的标记
                if (pickLocationMarker) {
                    pickLocationMarker.setMap(null);
                }

                // 创建新标记
                pickLocationMarker = new AMap.Marker({
                    position: lnglat,
                    map: pickLocationMap,
                    animation: 'AMAP_ANIMATION_DROP'
                });

                // 更新经纬度输入框
                $('#restaurantLatitude').val(lnglat.getLat().toFixed(6));
                $('#restaurantLongitude').val(lnglat.getLng().toFixed(6));

                // 获取地址
                AMap.plugin('AMap.Geocoder', function () {
                    const geocoder = new AMap.Geocoder();
                    geocoder.getAddress(lnglat, function (status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            const address = result.regeocode.formattedAddress;
                            $('#restaurantAddress').val(address);
                            console.log("获取到地址:", address);
                        } else {
                            console.error("获取地址失败:", status, result);
                        }
                    });
                });
            }

            // 图片预览
            $('#restaurantImage').change(function () {
                const file = this.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        $('#imagePreview').html(`<img src="${e.target.result}" class="img-fluid">`);
                    };
                    reader.readAsDataURL(file);
                }
            });

            // 保存餐厅信息
            $('#saveRestaurantBtn').click(function () {
                // 表单验证
                if (!$('#restaurantName').val() || !$('#restaurantCuisineType').val() ||
                    !$('#restaurantAddress').val() || !$('#restaurantPriceLevel').val() ||
                    !$('#restaurantLatitude').val() || !$('#restaurantLongitude').val()) {
                    alert('请填写必填字段');
                    return;
                }

                // 检查是否有图片文件
                const imageFile = $('#restaurantImage')[0].files[0];
                const restaurantId = $('#restaurantId').val();

                // 如果没有选择图片且不是编辑模式（或编辑模式下没有原图片），显示错误
                if (!imageFile && !restaurantId) {
                    alert('请上传餐厅图片');
                    return;
                }

                // 如果有图片文件，先上传图片
                if (imageFile) {
                    const formData = new FormData();
                    formData.append('file', imageFile);

                    $.ajax({
                        url: '/api/restaurants/upload-image',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                            if (res.code === 200) {
                                // 图片上传成功，继续保存餐厅信息
                                saveRestaurantWithImage(res.data);
                            } else {
                                alert('图片上传失败: ' + res.msg);
                            }
                        },
                        error: function (xhr) {
                            console.error('图片上传失败:', xhr);
                            alert('图片上传失败');
                        }
                    });
                } else {
                    // 编辑模式下没有选择新图片，使用原图片
                    const existingImageUrl = $('#imagePreview img').attr('src');
                    saveRestaurantWithImage(existingImageUrl);
                }
            });

            // 保存餐厅信息（带图片URL）
            function saveRestaurantWithImage(imageUrl) {
                // 构建JSON数据
                const restaurantData = {
                    name: $('#restaurantName').val(),
                    cuisineType: $('#restaurantCuisineType').val(),
                    address: $('#restaurantAddress').val(),
                    priceLevel: parseInt($('#restaurantPriceLevel').val()),
                    description: $('#restaurantDescription').val(),
                    latitude: $('#restaurantLatitude').val(),
                    longitude: $('#restaurantLongitude').val(),
                    image: imageUrl
                };

                // 添加ID（如果是编辑）
                const restaurantId = $('#restaurantId').val();
                if (restaurantId) {
                    restaurantData.id = restaurantId;
                }

                // 发送请求
                $.ajax({
                    url: restaurantId ? `/api/restaurants/${restaurantId}` : '/api/restaurants',
                    type: restaurantId ? 'PUT' : 'POST',
                    data: JSON.stringify(restaurantData),
                    contentType: 'application/json',
                    success: function (res) {
                        if (res.code === 200) {
                            // 关闭模态框
                            bootstrap.Modal.getInstance(document.getElementById('restaurantModal')).hide();

                            // 重新加载标记
                            loadMarkers();

                            // 显示成功消息
                            alert(restaurantId ? '餐厅信息已更新' : '餐厅已添加');
                        } else {
                            alert(res.msg || '操作失败');
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error("保存餐厅信息失败:", xhr.status, xhr.responseText);
                        alert('操作失败: ' + (xhr.responseJSON ? xhr.responseJSON.error : error));
                    }
                });
            }

            // 打开评论模态框
            function openReviewModal(restaurantId) {
                // 重置表单
                $('#reviewForm')[0].reset();
                $('#reviewRestaurantId').val(restaurantId);
                $('#reviewRating').val('');
                $('.rating-input i').removeClass('fas').addClass('far');
                $('#reviewImagePreview').empty();

                // 显示模态框
                const reviewModal = new bootstrap.Modal(document.getElementById('reviewModal'));
                reviewModal.show();
            }

            // 评分星级点击事件
            $('.rating-input i').click(function () {
                const rating = $(this).data('rating');
                $('#reviewRating').val(rating);

                // 更新星级显示
                $('.rating-input i').removeClass('fas').addClass('far');
                $('.rating-input i').each(function () {
                    if ($(this).data('rating') <= rating) {
                        $(this).removeClass('far').addClass('fas');
                    }
                });
            });

            // 评论图片预览
            $('#reviewImages').change(function () {
                const files = this.files;
                $('#reviewImagePreview').empty();

                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        $('#reviewImagePreview').append(`
                            <div style="width: 100px; height: 100px; overflow: hidden;">
                                <img src="${e.target.result}" class="img-fluid">
                            </div>
                        `);
                    };
                    reader.readAsDataURL(file);
                }
            });

            // 保存评论
            $('#saveReviewBtn').click(function () {
                // 表单验证
                if (!$('#reviewRating').val() || !$('#reviewContent').val()) {
                    alert('请填写评分和评论内容');
                    return;
                }

                // 获取图片文件
                const files = $('#reviewImages')[0].files;
                const imageUrls = [];
                let uploadedCount = 0;

                // 如果没有图片，直接提交评论
                if (files.length === 0) {
                    submitReview(imageUrls);
                    return;
                }

                // 上传图片
                for (let i = 0; i < files.length; i++) {
                    const formData = new FormData();
                    formData.append('file', files[i]);

                    $.ajax({
                        url: '/api/restaurants/upload-image',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                            if (res.code === 200) {
                                imageUrls.push(res.data);
                                uploadedCount++;

                                // 所有图片上传完成后提交评论
                                if (uploadedCount === files.length) {
                                    submitReview(imageUrls);
                                }
                            } else {
                                alert('图片上传失败: ' + res.msg);
                            }
                        },
                        error: function (xhr) {
                            console.error('图片上传失败:', xhr);
                            alert('图片上传失败');
                            uploadedCount++;

                            // 即使有图片上传失败，也继续提交评论
                            if (uploadedCount === files.length) {
                                submitReview(imageUrls);
                            }
                        }
                    });
                }
            });

            // 提交评论函数
            function submitReview(imageUrls) {
                // 构建JSON数据
                const reviewData = {
                    restaurantId: $('#reviewRestaurantId').val(),
                    rating: $('#reviewRating').val(),
                    content: $('#reviewContent').val(),
                    imageUrls: imageUrls
                };

                // 发送请求
                $.ajax({
                    url: '/api/restaurants/reviews',
                    type: 'POST',
                    data: JSON.stringify(reviewData),
                    contentType: 'application/json',
                    success: function (res) {
                        if (res.code === 200) {
                            // 关闭模态框
                            bootstrap.Modal.getInstance(document.getElementById('reviewModal')).hide();

                            // 显示成功消息
                            alert('评论已提交');

                            // 刷新餐厅信息
                            showRestaurantInfo($('#reviewRestaurantId').val());
                        } else {
                            alert('评论提交失败: ' + res.msg);
                        }
                    },
                    error: function (xhr) {
                        console.error('评论提交失败:', xhr);
                        alert('评论提交失败');
                    }
                });
            }
        });
    </script>
</body>

</html>